<template>
  <el-container>
    <el-header>
      <div class="report_header" ref="headerHeight">
        <div class="report_header_left"></div>
        <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
          <svg-icon class="primary" :icon-class="$route.meta.icon"/>
          <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
        </div>
        <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
          <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px;justify-content: flex-end;">
            <div class="report_header_date">
              <el-date-picker
                style="width: 100%;"
                v-model="query.date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="report_header_query" v-if="mchType==0||mchType==3">
              <el-select v-model="query.sysMchId" clearable placeholder="请选择商户"
                         filterable  value-key="id" :filter-method="querySysmch" @change="changeSysMch" >
                <el-option v-for="item in mchIdOptions" :key="item.id"   :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </div>
<!--            <div class="report_header_query">-->
<!--              <el-select clearable  v-model="query.title" placeholder="请选择类型" >-->
<!--                <el-option label="新人礼" :value="Number(0)"></el-option>-->
<!--                <el-option label="消费送" :value="Number(1)"></el-option>-->
<!--                <el-option label="扫码送" :value="Number(2)"></el-option>-->
<!--                <el-option label="满减"   :value="Number(3)"></el-option>-->
<!--                <el-option label="满折"   :value="Number(4)"></el-option>-->
<!--                <el-option label="满赠"   :value="Number(5)"></el-option>-->
<!--                <el-option label="满包邮" :value="Number(6)"></el-option>-->
<!--              </el-select>-->
<!--            </div>-->
            <div class="report_header_query">
              <el-select clearable v-model="value" placeholder="请选择状态" >
                <el-option label="待审核" :value="0"></el-option>
                <el-option label="已审核" :value="1"></el-option>
                <el-option label="已过期" :value="2"></el-option>
              </el-select>
            </div>
          </div>
          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryAd">查询</el-button>
          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
                     v-permission="['springscreen.add']">新增</el-button>
        </div>
      </div>
    </el-header>
    <div class="pd10">
      <el-table
        :data="adForm"
        border
        v-loadMore="[payLoads,'promotion-list']"
        style="width: 100%">
        <el-table-column
          label="排序"
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          prop="createDate"
          label="创建日期"
          width="100">
          <template slot-scope="{row}">
            <span>{{row.createDate | dateFormatter}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="促销标题">
        </el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          width="80">
          <template slot-scope="scope">
            <span>{{scope.row.type | watchType}}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="overlying"
          label="是否首单"
          width="80">
          <template slot-scope="scope">
            <el-tag type="success">
              <span>{{scope.row.firsted | watchFirsted}}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="overlying"
          width="110"
          label="单品活动叠加">
          <template slot-scope="scope">
            <el-tag type="success">
              <span>{{scope.row.overlying | watchOverlying}}</span>
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="beginDate"
          label="开始时间"
          width="160">
          <template slot-scope="{row}">
            <span>{{row.beginDate | datetimeFormatter}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="endDate"
          label="结束时间"
          width="160">
          <template slot-scope="{row}">
            <span>{{row.endDate | datetimeFormatter}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="功能"
          width="110"
          align="center"
          fixed="right"
          v-permission="['springscreen.audit']"
        >
          <template slot-scope="scope" >
            <el-button v-show="scope.row.status == 0" @click="selectStatus(scope.row)" type="primary" size="mini" >审核</el-button>
            <ExportList2Excel style="height: 30px;width: 80px;font-size: 12px;display: flex;justify-content: center;align-items: center;background-color: #1890ff;color: white" ref="exportList2Excel"v-show="scope.row.status == 1&&scope.row.type==2" @handleExport="handleExport(scope.row)" name="二维码" />
            <el-button v-show="scope.row.status == 1&&scope.row.type==2" @click="downLoadClick(scope.row)" type="primary" size="mini" > <i style="color: white;margin-right: 5px" class="el-icon-download"></i>二维码</el-button>
            <el-tag type="success" v-show="scope.row.status == 1&&scope.row.type!=2">
              <span>已审核</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="80" >
          <template slot-scope="scope">
            <div>
              <el-tooltip class="item" effect="dark" content="编辑" placement="top-start" v-permission="['springscreen.edit']">
                <a @click="editClick(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit"></i>
                </a>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start" v-permission="['springscreen.del']">
                <a style="margin-left: 10px" @click="deleteAd(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="loadPromotion"></pagination>
    </el-footer>
    <examine ref="examine" @loadPromotion="loadPromotion"></examine>
  </el-container>
</template>

<script>
  import Pagination from '@/components/Pagination';
  import {EventBus} from '@/api/eventBus'
  import {exportQrcode} from '@/api/qrcode'
  import loadMore from '@/utils/loadMore.js'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import ExportList2Excel from "@/components/ExportList2Excel";
  import elDragDialog from '@/directive/el-drag-dialog'
  import SingleUpload from '@/components/Upload/singleUpload'
  import giftList from './components/gift'
  import editGift from './components/editGift'
  import coupon from './components/coupon'
  import editCoupon from './components/editCoupon'
  import examine from './components/examine'
  import { del, find, list, save, update } from '../../api/promotion'
  import data from '../evaluationOrder/content'
  import { getInfo, list as sysMchList } from '@/api/sysMch'
  import { exportList } from '@/api/shipping'
  import { dateFormatter } from '@/filters' // base on element-ui
  import utils from '../../utils/utils.js'
  export default {
    directives: {elDragDialog,permission,loadMore},
    name: 'springscreen-list',
    activated() {
      this.payLoads = new Date().getTime();
    },
    data(){
      return{
        value:'',
        promotionType:0,
        total:0,
        payLoads:'',
        editVisible:false,
        clicked:false,
        hidden:false,
        adForm:[],
        queryType:true,
        giftTypeList:[],
        pageNum:1,
        mchType:'0',
        mchIdOptions:[],
        query: {
          sysMchId:'',
          title: '',
          date:[]
        },
        keyword: {
          title: '',
          date:[]
        },
        pickerOptions: {//时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        pageSize:20,
        dialogFormVisible: false,
        rules: {
          type:[ {required: true, message: '请输入选择类型', trigger: 'blur'},],
          agioRate:[
            {required: true, message: '请输入满减比例', trigger: 'blur'},
          ],
          amount:[
            {required: true, message: '请输入金额', trigger: 'blur'},
          ],
          title:[
            {required: true, message: '请输入促销标题', trigger: 'blur'},
          ],
          quantity:[
            {required: true, message: '请输入数量', trigger: 'blur'},
          ],
          memo:[
            {required: true, message: '请输入等级描述', trigger: 'blur'},
          ],
          enterpriseId:[
            {required: true, message: '请输入所属企业', trigger: 'blur'},
          ],
          integer:[
            {required: true, message: '请输入优先级', trigger: 'blur'},
          ],
          introduction:[
            {required: true, message: '请输入促销说明', trigger: 'blur'},
          ],
        },
        addPromotion:{
          givenAmount:0,
          agioRate:0,
          amount:0,
          createDate:'',
          firsted:false,
          giftType:'',
          gifts:[],
          introduction:'',
          minimumPrice:0,
          modifyDate:'',
          orders:0,
          overlying:false,
          thumbnail:'',
          title:'',
          type:''
        },
        editPromotion:{
          id:'',
          givenAmount:0,
          agioRate:0,
          amount:0,
          firsted:false,
          giftType:'',
          gifts:[
            {
              promotionId:'',
              giftId:'',
              availableQuantity:0,
              giftName:'',
              quantity:0}
          ],
          introduction:'',
          minimumPrice:0,
          modifyDate:'',
          orders:0,
          overlying:false,
          thumbnail:'',
          title:'',
          type:0
        }
      }
    },
    components:{SingleUpload,giftList,coupon,editGift,editCoupon,examine,Pagination,ExportList2Excel},
    created() {
      this.loadSysmch('')
      this.loadMch()
      this.loadPromotion()
      EventBus.$on('springscreen-add', res => { // 监听新增完毕
        // 更新列表数组
        this.adForm.splice(0, 0, res)
      });
      EventBus.$on('springscreen-edit', res => { // 监听新增完毕
        // 更新列表数组
        for (var i = 0; i < this.adForm.length; i++) {
          if (this.adForm[i].id == res.id) {
            this.$set(this.adForm, i,  res)
          }
        }
      })
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    filters:{
      watchType(val){
        const  typeName=['新人礼','消费送','扫码送','满减','满折','满赠','满包邮','充值送'];
        return typeName[val];
      },
      watchFirsted(val){
        if (val===true){
          return '有限'
        }else if (val ===false){
          return '不限'
        }
      },
      watchOverlying(val){
        if (val===true){
          return '允许叠加'
        }else if (val ===false){
          return '不允许叠加'
        }
      },
      watchGiftType(val){
        if (val==0){
          return '礼品'
        }else if (val ==1){
          return '优惠券'
        }
      },
      watchAmountType(val){
        if (val==3){
          return '满减金额'
        }else if (val==7){
          return '充值金额'
        }
      }
    }
    ,
    methods:{
      //下载模板的函数
      handleExport(id) {
        let _this= this
        //要导出函数携带的参数
        //要导出函数携带的参数
        let data ={}
        // data.tHeader = ["商品编号","地址","收货人","商品名称","联系电话","货号条码","数量","送货单号","规格","物流单号","单位"]
        data.tHeader = ["编码","二维码"]
        // data.filterVal = ["id","address","consignee","name","phone","productSn","quantity","sn","spec","trackingNo","unit"]
        data.filterVal = ["code","q"]
        data.filename = "扫码活动";
        exportQrcode({
          promotionId:id.id
        }).then(res=>{
          data.list=res.data
          _this.$refs.exportList2Excel.handleDownload(data)
        }).catch(error=>{
          _this.$refs.exportList2Excel.unlockLoading()
        })
        this.$refs.exportList2Excel.handleDownload(data);

      },
      loadSysmch(query){
        sysMchList({ name: query }).then(res => {

          this.mchIdOptions = res.data.data.filter(val => { return val.mchType == 3||val.mchType == 1 })
        }).catch(err => { console.log(err) })
      },
      changeSysMch(){
        this.loadPromotion()
      },
      querySysmch(query){
        this.loadSysmch(query)
      },
      loadMch(){
        getInfo().then(res=>{
          this.mchType=res.data.mchType
        })
      },
      downLoadClick(data){

        this.handleExport(data)
      },
      resetAd() {
        this.value='';
        this.query.title = '';
        this.query.date=[];
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadPromotion()
      },
      queryAd(){
        this.keyword = this.query;
        this.pageNum = 1
        this.loadPromotion()
      },
      loadPromotion(){
        if(utils.isNull(this.keyword.date)){
          this.keyword.date = []
        }
        if(utils.isNull(this.value)){
          this.value = ''
        }
        if(utils.isNull(this.keyword.title)){
          this.keyword.title= ''
        }
        if(utils.isNull(this.query.sysMchId)){
          this.query.sysMchId = ''
        }
        let params = new URLSearchParams();
        params.append('pageNum', this.pageNum);
        params.append('mchId',this.query.sysMchId)
        params.append('pageSize', this.pageSize);
        params.append('type',0)
        params.append('startDate', this.keyword.date.length > 0 ? this.keyword.date[0] : '');
        params.append('endDate', this.keyword.date.length > 0 ? this.keyword.date[1] : '');
        params.append('promotionType',this.promotionType)
        params.append('status',this.value)
        list(params).then(response =>{
          this.adForm=response.data.data
          this.total = response.data.total
        }).catch(error =>{
          console.log('error!!')
        })
      },
      selectStatus(data){
        this.$refs.examine.editVisible=true
        this.$refs.examine.findPromotion(data.id)
      },
      deleteAd(data) {
        console.log(data)
        var _this = this;
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(data.id).then(response => {
            console.log(response)
            _this.adForm.forEach(function (item, index) {
              if (item.id == data.id) {
                _this.adForm.splice(index, 1)
              }
            });
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
          }).catch(error => {
            console.log('error!!')
          });
        }).catch(() => {
        })
      },
      addClick(){
        this.$router.push({
          path: '/springscreen/add'
        })
      },
      editClick(row){
        this.$router.push({
          path: '/springscreen/edit', query: {id: row.id}
        })
      },
      findPromotion(){
        find(this.editPromotion.id).then(response =>{
          this.editPromotion=response.data.promotion;
        })
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 266//减去页面上固定高度height
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 220//减去页面上固定高度height
            }
          })();
        };
      },
      comeIn() {
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220//减去页面上固定高度height
      },
      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 266//减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 220//减去页面上固定高度height
        }
      },
    },



  }
</script>

<style scoped>
  .popup_content {
    padding-bottom: 0px !important;
  }
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  /deep/ .el-dialog__header {
    border: 1px solid #eeeeee !important;
    padding: 15px !important;
  }

  /deep/ .el-dialog__body {
    padding: 0px 20px !important;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
</style>
